package com.mallcai.bigdata.ladon.utils;

import com.cake.bigdata.starter.exception.error.CommonErrorCode;
import org.apache.commons.lang3.StringUtils;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-18 20:51
 */
public class ExceptionUtils {

    //打印异常堆栈信息
    public static String getStackTraceString(Throwable ex){
        StackTraceElement[] traceElements = ex.getStackTrace();

        StringBuilder traceBuilder = new StringBuilder();

        if (traceElements != null && traceElements.length > 0) {
            for (StackTraceElement traceElement : traceElements) {
                traceBuilder.append(traceElement.toString());
                traceBuilder.append("\n");
            }
        }
        return traceBuilder.toString();
    }

    //构造异常堆栈信息
    public static String buildErrorMessage(Exception ex) {

        String stackTrace = getStackTraceString(ex);
        String exceptionType = ex.getClass().getSimpleName();
        String exceptionMessage = ex.getMessage();

        String result = String.format("%s : %s \r\n %s", exceptionType, exceptionMessage, stackTrace);

        return result;
    }

    public static String getSimpleMessage(Exception ex){
        String message = ex.getMessage();
        if (StringUtils.isEmpty(message)){
            message = CommonErrorCode.EXCEPTION.getMessage();
        }
        return message;
    }
}